package com.xbongbong.workflow.service.operator.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.workflow.domain.entity.WorkflowNodeEntity;
import com.xbongbong.paas.pojo.workflow.WorkflowDataPojo;
import com.xbongbong.workflow.pojo.WorkflowOperationsPojo;
import com.xbongbong.workflow.service.operator.WorkflowOperatorFieldHandler;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/06/18 16:27
 */
@Service("workflowOperatorDeptHandlerImpl")
public class WorkflowOperatorDeptHandlerImpl implements WorkflowOperatorFieldHandler {


    @Override
    public List<Integer> type() {
        return Arrays.asList(FieldTypeEnum.DEPT.getType());
    }

    @Override
    public Object handlerThisFormField(PaasFormDataEntity paasFormDataEntity, JSONObject data, FieldAttrEntity fieldAttrEntity,
                                       WorkflowDataPojo workflowDataPojo, WorkflowOperationsPojo workflowOperationsPojo) throws XbbException {
        return data.get(fieldAttrEntity.getAttr());
    }

    @Override
    public Object handlerTargetFormField(PaasFormDataEntity paasFormDataEntity, JSONObject data, FieldAttrEntity fieldAttrEntity,
                                         FieldAttrEntity targetField, WorkflowDataPojo workflowDataPojo,
                                         WorkflowOperationsPojo workflowOperationsPojo, WorkflowNodeEntity workflowNodeEntity) throws XbbException {
        if (Objects.isNull(workflowDataPojo.getValue())) {
            return data.get(fieldAttrEntity.getAttr());
        }
        return workflowDataPojo.getValue();
    }

    @Override
    public Object handlerFixedValue(FieldAttrEntity targetField, WorkflowDataPojo workflowDataPojo, WorkflowOperationsPojo workflowOperationsPojo, WorkflowNodeEntity workflowNodeEntity) throws XbbException {
        JSONObject user = JSON.parseObject(JSON.toJSONString(workflowOperationsPojo.getValue()));
        return user.get("id");
    }

    @Override
    public Object formulaHandlerThisField(FieldAttrEntity fieldAttrEntity, PaasFormDataEntity formDataEntity, JSONObject data, Long formId, Integer businessType, String corpid)  throws XbbException {
        return JSON.toJSONString(data.get(fieldAttrEntity.getAttr()));
    }

    @Override
    public Object formulaHandlerTargetField(Object value, WorkflowOperationsPojo workflowOperationsPojo, FieldAttrEntity targetField, WorkflowNodeEntity workflowNodeEntity, String corpid) throws XbbException {
        if (Objects.isNull(value)) {
            return null;
        }
        return JSON.parseObject(JSON.toJSONString(value), Long.class);
    }
}
